package com.example.android.ui.login;

import com.example.android.bean.Login;
import com.example.android.bean.LoginToken;

import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Scheduler;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class LoginPresenter implements LoginContract.ILoginPresenter {
    private LoginContract.ILoginView loginView;
    LoginContract.ILoginModel loginModel;
    public LoginPresenter(LoginContract.ILoginView loginView){
        this.loginView = loginView;
        loginModel = new LoginModel();
    }

    @Override
    public void getLoginData(String username, String password) {
        loginModel.getLoginData(username,password)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Login>() {
                    @Override
                    public void accept(Login login) throws Throwable {
                        loginView.getLoginSuccess(login);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Throwable {
                        loginView.getLoginError(throwable);
                    }
                });

    }

    @Override
    public void getTokenData(int userId, String token) {
        loginModel.getTokenData(userId,token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<LoginToken>>() {
                    @Override
                    public void accept(List<LoginToken> loginTokens) throws Throwable {
                        loginView.getTokenSuccess(loginTokens.get(0));
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Throwable {
                        loginView.getLoginError(throwable);
                    }
                });
    }
}
